<template>
  <div class="p-2">
    <el-card shadow="never">
      <el-table v-loading="loading" :data="assetCatalogList">
        <el-table-column label="台账名称" align="center">
          <template #default="scope">
            <el-select
              class="slese"
              id="123"
              @visible-change="handleVisibleChange"
              v-model="scope.row.tzmodel"
              placeholder="请选择台账"
              ref="selectRef"
              @change="changed($event,scope.row)"
              :disabled="routeType == 'edit'"
            >
              <el-option class="tzDropdown" v-for="item in tzOptions" :key="item.id" :label="item.name" :value="item.id" />
              <p class="el-select-dropdown__empty" v-if="loadingmore">加载中</p>
              <p class="el-select-dropdown__empty" v-if="loadingnomore">无数据</p>
            </el-select>
          </template>
        </el-table-column>

        <el-table-column label="类别" align="center">
          <template #default="scope">
            <el-select style="width:100%;" v-model="scope.row.category" placeholder="请选择类别" disabled>
              <el-option v-for="item in categoryData" :key="item.id" :label="item.category" :value="item.id" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="型号" align="center">
          <template #default="scope">
            {{scope.row.model}}
            <!-- <el-input v-model="scope.row.model" placeholder="请输入型号" clearable :disabled="true" /> -->
          </template>
        </el-table-column>
        <el-table-column label="单位" align="center" width="80px">
          <template #default="scope">
            {{scope.row.unit}}
            <!-- <el-input v-model="scope.row.unit" placeholder="请输入单位" clearable :disabled="true" /> -->
          </template>
        </el-table-column>
        <el-table-column label="库存数量" align="center" width="60px">
          <template #default="scope">
            {{scope.row.quantity}}
            <!-- <el-input v-model="scope.row.quantity" placeholder="请输入库存数量" clearable :disabled="true" /> -->
          </template>
        </el-table-column>
        <el-table-column label="单价" align="center">
          <template #default="scope">
            {{scope.row.univalence}}
            <!-- <el-input v-model="scope.row.univalence" placeholder="请输入单价" clearable :disabled="true" /> -->
          </template>
        </el-table-column>
        <el-table-column label="合计" align="center">
          <template #default="scope">
            {{scope.row.total}}
            <!-- <el-input v-model="scope.row.total" placeholder="请输入合计" clearable :disabled="true" /> -->
          </template>
        </el-table-column>
        <!-- <el-table-column label="备注" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.remark" placeholder="请输入备注" clearable />
          </template>
        </el-table-column> -->

        <el-table-column label="项目名称" align="center">
          <template #default="scope">
            <el-select
              class="slese"
              @visible-change="xmhandleVisibleChange"
              v-model="scope.row.xmmodel"
              placeholder="请选择项目"
              ref="selectRef"
              @change="xmchanged($event,scope.row)"
            >
              <el-option class="xmDropdown" v-for="item in xmOptions" :key="item.id" :label="item.projectName" :value="item.id" />
              <p class="el-select-dropdown__empty" v-if="loadingmore">加载中</p>
              <p class="el-select-dropdown__empty" v-if="loadingnomore">无数据</p>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="出库数量" align="center">
          <template #default="scope">
            <el-input-number v-model="scope.row.outboundQuantity" placeholder="请输入出库数量" clearable width="100px" />
          </template>
        </el-table-column>
        <el-table-column label="出库时间" align="center">
          <template #default="scope">
            <el-date-picker
              v-model="scope.row.outboundTime"
              value-format="YYYY-MM-DD"
              type="date"
              placeholder="Pick a day"
              size="default"
              width="80px"
            />
          </template>
        </el-table-column>
        <el-table-column v-if="routeType == 'add'" label="操作" align="center" class-name="small-padding fixed-width" width="50px">
          <template #default="scope">
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="assetCatalogList = assetCatalogList.filter(item => item != scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <div style="display: flex;justify-content: center;margin-top: 20px;">
      <el-button type="primary" icon="Plus" @click="addLine">追加一条</el-button>
      <el-button v-if="routeType == 'add'" type="success" icon="Position" @click="handleQuery">提交全部</el-button>
      <el-button v-else type="success" icon="Position" @click="handleQuery">提交修改</el-button>
      <el-button @click="goBack">返 回</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { listAssetLedger } from '@/api/business/assetLedger';
import { listProject } from '@/api/business/project';
import { getAssetOutboundRecords, addAssetOutboundRecords, updateAssetOutboundRecords } from '@/api/business/assetOutboundRecords/index';
import { AssetOutboundRecordsVO } from '@/api/business/assetOutboundRecords/types';
import { ProjectQuery } from '@/api/business/project/types';
import { listAssetCategory } from '@/api/business/assetCategory/index';

import { ref } from 'vue'

const tzOptions = ref()
const xmOptions = ref()

const route = useRoute()
const routeType = ref('add');

const assetCatalogList = ref<AssetOutboundRecordsVO[]>([]);
const listItem = {
  tzmodel:'',
  xmmodel:'',
  id: '',
  type: '2',
  category: '',
  propertyAssetLedgerId: '',
  name: '',
  model: '',
  unit: '',
  quantity: '',
  univalence: '',
  total: '',
  outboundTime: '',
  outboundQuantity:0,
  remark: '',
}
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const loading = ref(true);
// const { tzqueryParams, form, rules } = toRefs(data);
const tzqueryParams = ref<ProjectQuery>({
  pageNum: 1,
  pageSize: 8,
  type:2
})
const xmqueryParams = ref<ProjectQuery>({
  pageNum: 1,
  pageSize: 8,
})
const tztotal = ref(0);
const xmtotal = ref(0);
const categoryData = ref([])

// 追加一条
const addLine = () => {
  assetCatalogList.value.push(JSON.parse(JSON.stringify(listItem)))
}

const hasNoEmptyValues = () => {
  let flag = true
  assetCatalogList.value.forEach(element => {
    if(routeType.value == 'edit') {
      if(element.projectId == '' || element.propertyAssetLedgerId == '' || element.outboundTime == '' || element.projectId == null || element.propertyAssetLedgerId == null || element.outboundTime == null ){
        ElMessage.error('请将信息填写完成！')
        flag = false
      }else if(element.outboundQuantity<1){
        ElMessage.error('出库数量必须大于零！')
        flag = false
      }else {
        flag = true
      }
    }else {
      if(element.projectId == '' || element.propertyAssetLedgerId == '' || element.outboundTime == '' || element.projectId == null || element.propertyAssetLedgerId == null || element.outboundTime == null ){
        ElMessage.error('请将信息填写完成！')
        flag = false
      }else if(element.outboundQuantity<=0){
        ElMessage.error('出库数量必须大于零！')
        flag = false
      }
      else if(element.outboundQuantity > element.quantity){
        ElMessage.error('出库数量不得大于库存数量！')
        flag = false
      }else {
        flag = true
      }
    }
  })
  return flag
}


// 提交全部
const handleQuery = async () => {
  console.log(assetCatalogList.value);
  if(hasNoEmptyValues()) {
    if(routeType.value == 'edit') {
      await updateAssetOutboundRecords({'propertyAssetOutboundRecordsListBo':assetCatalogList.value}).then(() =>  {proxy?.$modal.msgSuccess("修改成功");});
      await goBack()
    }else {
      await addAssetOutboundRecords({'propertyAssetOutboundRecordsListBo':assetCatalogList.value}).then(() =>  {proxy?.$modal.msgSuccess("新增成功");});
      await goBack()
    }
  }
}

/** 返回 */
const goBack = () =>{
  const obj = { path: "/NotFixedAssetManagement/NotFixedAssetManagementOutbound/NotFixedAssetManagementOutboundList" };
  proxy?.$tab.closeOpenPage(obj);
}

/** 查询项目管理列表 */
const getList = async () => {
  loading.value = true;
  const tz = await listAssetLedger(tzqueryParams.value);
  const xm = await listProject(xmqueryParams.value);
  tzOptions.value = tz.rows
  xmOptions.value = xm.rows
  // projectList.value = res.rows;
  tztotal.value = tz.total;
  xmtotal.value = xm.total;
  loading.value = false;
}

const handleVisibleChange = (visible: any) => {
  try {
    if (visible) {
      // 如果下拉框显示
      // let tzDropdown: any = document.querySelector('.el-select-dropdown__wrap')
      let tzDropdown: any = document.getElementsByClassName('tzDropdown')[0].parentElement.parentElement
      // 监听下拉框滚动事件
      tzDropdown.addEventListener('scroll', tzloadNextPage)
    } else {
      // 如果下拉框隐藏
      let tzDropdown: any = document.getElementsByClassName('tzDropdown')[0].parentElement.parentElement
      // 移除下拉框滚动事件监听
      tzDropdown.removeEventListener('scroll', tzloadNextPage)
    }
  } catch (error) {}
}
const xmhandleVisibleChange = (visible: any) => {
  try {
    if (visible) {
      // 如果下拉框显示
      let xmDropdown: any = document.getElementsByClassName('xmDropdown')[0].parentElement.parentElement
      // 监听下拉框滚动事件
      xmDropdown.addEventListener('scroll', xmloadNextPage)
    } else {
      // 如果下拉框隐藏
      let xmDropdown: any = document.getElementsByClassName('xmDropdown')[0].parentElement.parentElement
      // 移除下拉框滚动事件监听
      xmDropdown.removeEventListener('scroll', xmloadNextPage)
    }
  } catch (error) {}
}
const loadingmore = ref(false)
const loadingnomore = ref(false)
const tzloadNextPage = async () => {
  // let tzDropdown: any = document.querySelector('.el-select-dropdown__wrap');
  let tzDropdown: any = document.getElementsByClassName('tzDropdown')[0].parentElement.parentElement;
  // 判断下拉框是否触底
  if (tzDropdown.scrollTop + tzDropdown.clientHeight >= tzDropdown.scrollHeight - 2) {
    loadingnomore.value = false
    loadingmore.value = true
    if (tzOptions.value.length + 1 <= tztotal.value && loadingmore.value) {
      tzqueryParams.value.pageNum ++
      const res = await listAssetLedger(tzqueryParams.value)
      tzOptions.value.length + 1   <= tztotal.value?tzOptions.value.push(...res.rows):''
      loadingmore.value = false
    }else{
      loadingmore.value = false
    tzDropdown.removeEventListener('scroll', tzloadNextPage)
    loadingnomore.value = true
    }
  } else {
    loadingnomore.value = true
  }
}

const xmloadNextPage = async () => {
  // let xmDropdown: any = document.querySelector('.el-select-dropdown__wrap');
  let xmDropdown: any = document.getElementsByClassName('xmDropdown')[0].parentElement.parentElement;
  // 判断下拉框是否触底
  if (xmDropdown.scrollTop + xmDropdown.clientHeight >= xmDropdown.scrollHeight - 2) {
    loadingnomore.value = false
    loadingmore.value = true
    if (xmOptions.value.length + 1 <= xmtotal.value && loadingmore.value) {
      xmqueryParams.value.pageNum ++
      const res = await listProject(xmqueryParams.value)
      xmOptions.value.length + 1 <= xmtotal.value?xmOptions.value.push(...res.rows):''
      loadingmore.value = false
    }else{
      loadingmore.value = false
      xmDropdown.removeEventListener('scroll', xmloadNextPage)
      loadingnomore.value = true
    }
  } else {
    loadingnomore.value = true
  }
}
const changed = async (id,row)=> {
  tzOptions.value.forEach(element => {
    if(element.id == id) {
      row.category = element.category
      row.propertyAssetLedgerId = element.id
      row.name = element.name
      row.model = element.model?element.model:undefined
      row.unit = element.unit
      row.quantity = element.quantity
      row.univalence = element.univalence
      row.total = element.total
      // row.remark = element.remark
    }
  });
  // const res = await getAssetLedger(id);
  // console.log(res);

  // Object.assign(form.value, res.data);
}

const xmchanged = async (id,row)=> {
  xmOptions.value.forEach(element => {
    if(element.id == id) {
      row.projectName = element.projectName
      row.projectId = element.id
    }
  });
}

const getCategoryData = async () =>{
  const res = await listAssetCategory();
  categoryData.value = res.rows
}

onMounted(async () => {
  await getCategoryData()
  await getList()
  if(route.query.type == 'edit') {
    routeType.value = route.query.type
    getAssetOutboundRecords(route.query.id).then(res => {
      assetCatalogList.value = [res.data]
      assetCatalogList.value.forEach( element => {
        element.tzmodel = element.propertyAssetLedgerId
        element.xmmodel = element.projectId
      })
    })
  }else{
    addLine()
  }
  console.log(route.query.type);
})
</script>
<style>
.el-date-editor  {
  --el-date-editor-width: 122px;
}
</style>
